package com.banyuan.dao;

import com.banyuan.domain.User;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class UserUtils {
    private static File file = new File("/Users/edy/Desktop/user.txt");


    //查找
    public static List<User> listUser() throws IOException {
        List<User> userList = new ArrayList<>();
        List<String> stringList = FileUtils.readLines(file, "UTF-8");
        for (String s : stringList) {
            User user = strToUser(s);
            userList.add(user);
        }
        return userList;
    }



    //增加

    public static void addUser(User user) throws IOException {
        FileUtils.writeStringToFile(file,userToString(user)+"\n","UTF-8",true);
    }


    //通过用户名来删除一个User对象
    public static void deleteUser(String name) throws IOException {
        List<User> userList = listUser();
        FileUtils.writeStringToFile(file,"","UTF-8");
        for (User user : userList) {
            if (!(user.getName().equals(name))) {
                addUser(user);
            }
        }

    }



   //通过名字来找到这个USer对象
    public static User getUser(String name) throws IOException {
        List<User> userList = listUser();
        for (User user : userList) {
            if (user.getName().equals(name)) {
                return user;
            }
        }
        return null;
    }

    //修改
    public static void update(User findUser) throws IOException {
        List<User> userList = listUser();
        FileUtils.writeStringToFile(file,"","UTF-8");//清空文档
        for (User user : userList) {
            if (user.getName().equals(findUser.getName())) {
                addUser(findUser);
            } else {
                addUser(user);
            }
        }
    }
    // 查找
    public static List<User> findUser(String str) throws IOException {
        List<User> findList = new ArrayList<>();
        List<User> userList = listUser();
        for (User user : userList) {
            if (user.getName().contains(str)) {
                findList.add(user);
            }
        }
        return findList;
    }







    //String转USer对象
    public static User strToUser(String str) throws IOException {
        String[] split = str.split(",");
        User user = new User(split[0],split[1],split[2],split[3]);
          return user;
    }



    //User对象转String
    public static String userToString(User user) {
        return user.getName()+","+user.getAge()+","+user.getSex()+","+user.getAddress();
    }
}
